package com.joe.web.test;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

public class Rel {

    public static void main(String[] args) {

        Parent parent = new Parent();

        parent.setId(10);
        parent.setName("zhou");

        String[] names = new String[0];
        try {
            names = getFieldValueByFieldName("name", parent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(names);

        try {
            System.out.println(FieldUtils.readDeclaredField(parent,"name"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    public static String[] getFieldValueByFieldName(String fieldName, Object object) throws Exception {

        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        Method method = object.getClass().getMethod(getter, new Class[]{});
        Object result = method.invoke(object, new Object[]{});
        if (null != result) {
            return (String[]) result;
        }
        return new String[]{};
    }


}
